package com.contact_book.operations;

import com.contact_book.entity.Contact;
import com.contact_book.exception.ContactNotFoundException;
import com.contact_book.exception.FailedToHandleFileException;
import com.contact_book.util.CSVUtil;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class ContactManagerImpl implements ContactManager {

    private File file;
    private CSVUtil csvUtil;
    private List<Contact> contacts;

    public ContactManagerImpl(File file)
            throws FailedToHandleFileException {
        this.file = file;
        csvUtil = new CSVUtil(file);
        contacts = csvUtil.readContacts();
    }

    @Override
    public void addContact(Contact contact)
            throws FailedToHandleFileException {
        contacts.add(contact);
        csvUtil.saveContacts(contacts);
    }

    @Override
    public void showAllContacts() {
        System.out.println(FILE_HEADER);
        for (Contact contact : contacts) {
            System.out.println(contact.toString().replace("#", " "));
        }
        System.out.println("");
    }

    @Override
    public Contact findContact(String name)
            throws ContactNotFoundException {
        Contact contactToFind = null;
        for (Contact contact : contacts) {
            if (contact.getName().toLowerCase().contains(name.toLowerCase().trim())) {
                contactToFind = contact;
                break;
            }
        }
        if (contactToFind != null) {
            System.out.println(ContactManager.FILE_HEADER);
            System.out.println(contactToFind.toString().replace("#", " ") + "\n");
            return contactToFind;
        } else {
            throw new ContactNotFoundException(
                    "The contact with the name " + name + " was not found.");
        }
    }

    @Override
    public void deleteContact(String name)
            throws ContactNotFoundException, FailedToHandleFileException {
        Contact contactToDelete = null;
        for (Contact contact : contacts) {
            if (contact.getName().toLowerCase().contains(name.toLowerCase().trim())) {
                contactToDelete = contact;
                break;
            }
        }
        if (contacts.remove(contactToDelete)) {
            csvUtil.saveContacts(contacts);
        } else {
            throw new ContactNotFoundException(
                    "The contact with the name " + name + " was not found.");
        }

    }
}
